package appapi.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

public class FileUtil {
    /**
     * 获取文件后缀
     *
     * @param fileName
     * @return
     */
    public static String getSuffix(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 生成新的文件名
     *
     * @param fileOriginName 源文件名
     * @return
     */
    public static String getFileName(String fileOriginName) {
        return getUUID() + getSuffix(fileOriginName);
    }

    public static String getUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * @param file     文件
     * @param path     文件存放路径
     * @param fileName 源文件名
     * @return
     */
    public static String upload(MultipartFile file, String path, String fileName) {
        String newFileName = getFileName(fileName);
        // 生成新的文件名
        String realPath = path + newFileName;

        //使用原文件名
//        String realPath = path + "/" + fileName;

        File dest = new File(realPath);

        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }

        try {
            //保存文件
            file.transferTo(dest);
            return newFileName;
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

    public static String findfileInfo(String path,String fileName) {
        //查询路径
        File dest = new File(path);
        File[] fs = dest.listFiles();
        for (File f : fs) {               //遍历File[]数组
            if (!f.isDirectory())//若非目录(即文件)，则打印
            {
               if(f.getName().equals(fileName))
                return FileUtil.readTxt(f);
            }
        }
        return "";
    }

    public static String readTxt(File file){
      String s = "";
      try {
          InputStreamReader in = new InputStreamReader(new FileInputStream(file), "GB2312");
          BufferedReader br = new BufferedReader(in);
          StringBuffer content = new StringBuffer();
          while ((s = br.readLine()) != null) {
              content = content.append(s);
          }
          br.close();
          return content.toString();
      }catch (Exception ex)
      {
          return "";
      }
     }

    public static String findapk(String path) {
        //查询路径
        String realPath = path + "/Soft";
        File dest = new File(realPath);
        File[] fs = dest.listFiles();
        for (File f : fs) {               //遍历File[]数组
            if (!f.isDirectory())        //若非目录(即文件)，则打印
                return f.getName();
        }
        return "";
    }


    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath + fileName);
        out.write(file);
        out.flush();
        out.close();
    }


    public static void download(String filename, HttpServletResponse res) throws IOException {

        String path = System.getProperty("user.dir")+ "/file/";
        File file = new File(path + filename);

        // 发送给客户端的数据
        OutputStream outputStream = res.getOutputStream();
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        try {
            if (file.exists()) {
                // 读取filename
                bis = new BufferedInputStream(new FileInputStream(file));
                int i = bis.read(buff);
                while (i != -1) {
                    outputStream.write(buff, 0, buff.length);
                    outputStream.flush();
                    i = bis.read(buff);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
